package com.hgk.wanwan.main.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.common.dongqiuhui.apps.comm.tools.BallLog;
import com.hgk.appllication.MyApplication;
import com.hgk.wanwan.main.tool.MemoryStatus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.HttpStatus;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import width.hgk.wanwan.R;

//后台进行下载操作
/*
* 1.首先拿到更新apk文件的大小
*   1.2拿到手机内存空余大小，两者比较，判断是否要更新
* 2，判断网络是否正常，是否是在WiFi状态下，（没做）
* 3.得到下载的大小，展示下载进度
* */
public class UpdataService extends Service {
    // BT字节参考量
    private static final float SIZE_BT = 1024L;
    // KB字节参考量
    private static final float SIZE_KB = SIZE_BT * 1024.0f;
    // MB字节参考量
    private static final float SIZE_MB = SIZE_KB * 1024.0f;

    private final static int DOWNLOAD_COMPLETE = 1;// 完成
    private final static int DOWNLOAD_NOMEMORY = -1;// 内存异常
    private final static int DOWNLOAD_FAIL = -2;// 失败

    private String appName = null;//应用名字
    private String appUrl = null;//应用升级地址
    private File updateDir = null;//文件目录
    private File updataFile = null;//升级文件

    //通知栏
    private NotificationManager updataNotificationManger = null;
    private Notification updataNotification = null;

    private Intent updataIntent = null;//下载完成
    private PendingIntent updataPendingIntent = null;//在下载的时候

    public UpdataService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        appName = intent.getStringExtra("message");
        appUrl = intent.getStringExtra("url");
        appName = "玩儿";
        updataNotificationManger = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        updataNotification = new Notification();
        updataNotification.icon = R.drawable.icon;

        updataNotification.tickerText = appName+"正在下载";
        updataNotification.when = System.currentTimeMillis();

        updataIntent = new Intent(this, MyApplication.class);
        updataPendingIntent = PendingIntent.getActivity(this,0,updataIntent,0);
        updataNotification.contentIntent = updataPendingIntent;
        updataNotification.contentIntent.cancel();

        updataNotification.contentView = new RemoteViews(getPackageName(),R.layout.download_notification);
        updataNotification.contentView.setTextViewText(R.id.download_notice_name_tv,appName+"正在下载");
        updataNotification.contentView.setProgressBar(R.id.download__pb, 100, 0, false);

        updataNotification.contentView.setTextViewText(R.id.download_percent, "0MB");
        updataNotificationManger.notify(0, updataNotification);
        new UpLoadTask().execute();
    }


    public class UpLoadTask extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {
            return downloadUpdataFile(appUrl);
        }

        //利用doInBackground()中的到的结果来进行下载操作
        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            if (result instanceof Integer){
                if(result.equals(DOWNLOAD_COMPLETE)){
                    BallLog.e(" updata ","下载成功");
                    String cmd = "chmod 777"+updataFile.getPath();
                    try{
                        Runtime.getRuntime().equals(cmd);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    Uri uri = Uri.fromFile(updataFile);
                    //安装程序
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);
                    installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                    updataPendingIntent = PendingIntent.getActivity(UpdataService.this,0,installIntent,0);
                    updataNotification.contentIntent = updataPendingIntent;
                    updataNotification.contentView.setTextViewText(R.id.download_notice_name_tv,"下载完成");
                    updataNotification.tickerText = appName+"下载完成";
                    updataNotification.when = System.currentTimeMillis();
                    updataNotification.defaults = Notification.DEFAULT_SOUND;
                    updataNotification.flags |= Notification.FLAG_AUTO_CANCEL;//a|=b的意思就是把a和b按位或然后赋值给a   按位或的意思就是先把a和b都换成2进制，然后用或操作，相当于a=a|b
                    updataNotificationManger.notify(0,updataNotification);
                    UpdataService.this.startActivity(installIntent);
                    stopSelf();
                }else if(result.equals(DOWNLOAD_NOMEMORY)){
                    //如果内存出现问题
                    updataNotification.tickerText = appName+"下载失败";
                    updataNotification.when = System.currentTimeMillis();
                    updataNotification.contentView.setTextViewText(R.id.download_notice_name_tv,"下载失败");
                    updataNotification.flags |= Notification.FLAG_AUTO_CANCEL;
                    updataNotification.defaults = Notification.DEFAULT_SOUND;
                    updataNotificationManger.notify(0,updataNotification);
                    stopSelf();
                }else if(result.equals(DOWNLOAD_FAIL)){
                    //下载失败
                    updataNotification.tickerText = appName+"下载失败";
                    updataNotification.when = System.currentTimeMillis();
                    updataNotification.contentView.setTextViewText(R.id.download_notice_name_tv,"下载失败");
                    updataNotification.flags |= Notification.FLAG_AUTO_CANCEL;
                    updataNotification.defaults = Notification.DEFAULT_SOUND;
                    updataNotificationManger.notify(0,updataNotification);
                    stopSelf();
                }
            }
        }
    }

    private Object downloadUpdataFile(String appUrl) {
        double lastpercent = 0;
        double curpercent = 0;
        long totalSize = 0;   //总大小
        long downloadSize = 0;   //下载的大小
        URI uri = null;

        HttpGet httpGet = null;
        try {
            uri = new URI(appUrl);
            httpGet = new HttpGet(uri);
        } catch (URISyntaxException e) {
            String enxodeUrl = appUrl.replace(' ', '+');
            httpGet = new HttpGet(enxodeUrl);
            e.printStackTrace();
        }

        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
        FileOutputStream fos = null;
        InputStream ips = null;

        try {
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse != null) {
                int stateCode = httpResponse.getStatusLine().getStatusCode();
                if (stateCode == HttpStatus.SC_OK) {
                    HttpEntity entity = httpResponse.getEntity();
                    totalSize = entity.getContentLength();
                    //如果内存不可用
                    if (MemoryAvailable(totalSize)) {
                        ips = entity.getContent();
                        if (ips != null) {
                            fos = new FileOutputStream(updataFile, false);
                            byte buffer[] = new byte[1024*1000];
                            int readsize = 0;
                            while ((readsize = ips.read(buffer))!=-1) {
                                fos.write(buffer, 0, readsize);
                                downloadSize += readsize;
                                if(lastpercent==0||curpercent-lastpercent>5) {
                                    lastpercent = ((double)downloadSize/(double)totalSize)*100;
                                    updataNotification.contentView.setProgressBar(R.id.download__pb,100, (int) (((double)downloadSize/(double)totalSize)*100),false);
                                    updataNotification.contentView
                                            .setTextViewText(R.id.download_percent,
                                                    getMsgSpeed(downloadSize, totalSize));
                                    updataNotificationManger.notify(0,
                                            updataNotification);
                                }
                                curpercent= ((double)downloadSize/(double)totalSize)*100;
                            }
                            fos.flush();
                            //is.close();
                            //fos.close();
                            if (totalSize >= downloadSize) {
                                updataNotification.contentView.setProgressBar(R.id.download__pb,100, 100,false);
                                updataNotification.contentView
                                        .setTextViewText(
                                                R.id.download_percent,
                                                getMsgSpeed(totalSize, totalSize));
                                updataNotificationManger.notify(0,
                                        updataNotification);
                                return DOWNLOAD_COMPLETE;
                            } else {
                                return DOWNLOAD_FAIL;
                            }
                        }
                    }else {
                        if (httpGet != null) {
                            httpGet.abort();
                        }
                        return DOWNLOAD_NOMEMORY;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if (fos !=null)fos.close();
                if (ips!=null)ips.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            if (httpClient!=null)httpClient.getConnectionManager().shutdown();
        }
        return null;
    }

    //获取下载进度
    private CharSequence getMsgSpeed(long downloadSize, long totalSize) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(getSize(downloadSize));
        stringBuffer.append("/");
        stringBuffer.append(getSize(totalSize));
        stringBuffer.append(" ");
        return stringBuffer.toString();
    }
    /**
     * 获取大小
     * @param size
     * @return
     */
    public static String getSize(long size) {
        if (size >= 0 && size < SIZE_BT) {
            return (double) (Math.round(size * 10) / 10.0) + "B";
        } else if (size >= SIZE_BT && size < SIZE_KB) {
            return (double) (Math.round((size / SIZE_BT) * 10) / 10.0) + "KB";
        } else if (size >= SIZE_KB && size < SIZE_MB) {
            return (double) (Math.round((size / SIZE_KB) * 10) / 10.0) + "MB";
        }
        return "";
    }

    //判断内存可用大小
    private boolean MemoryAvailable(long totalSize) {
        totalSize += (1024 << 10);
        if (MemoryStatus.externalMemoryAvailable()) {
            if (MemoryStatus.getAvailableExternalMemorySize() <= totalSize) {
                if (MemoryStatus.getAvailableInternalMemorySize() > totalSize) {
                    createFile(false);
                    return true;
                } else {
                    return false;
                }
            } else {
                createFile(true);
                return true;
            }
        } else {
            if (MemoryStatus.getAvailableInternalMemorySize()<=totalSize){
                return false;
            }else{
                createFile(true);
                return true;
            }
        }
    }

    //sdca可用时创建文件
    private void createFile(boolean b) {
        if (b){
            updateDir = new File(Environment.getExternalStorageDirectory(),"waner");
        }else{
            updateDir = getFilesDir();
        }

        updataFile = new File(updateDir.getPath(),"waner"+".apk");
        if (!updateDir.exists()){
            updateDir.mkdirs();
        }
        if (!updataFile.exists()){
            try{
                updataFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
        }else{
            updataFile.delete();
            try{
                updataFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
